import axios from 'axios'
import store from '@/store'
import qs from 'qs'

let _refreshing: Promise<unknown> | null = null

function _refreshToken (refreshToken: string) {
  return axios
    .post('/front/user/refresh_token', qs.stringify({ refreshtoken: refreshToken }))
    .then(resp => {
      console.log('suc', resp)
      if (resp.data.state === 1) {
        store.commit('setUser', JSON.parse(resp.data.content))
      } else {
        const error = new Error('RefreshToken Failed') as (Error & {resp: unknown})
        error.resp = resp
        return Promise.reject(error)
      }
    })
}

export function refreshTokenByShare (refreshToken: string) {
  if (!_refreshing) {
    _refreshing = _refreshToken(refreshToken)
  }
  return _refreshing
}
